<template>
	<view class="handerimg flex-jc-ac">
		<view class="box" @click="handleUpHeaderImg">
			<view class="imgs"><image :src="info.upload_avatar ? info.upload_avatar.path_text : '/static/home/default_user.png'" mode="aspectFill"></image></view>
			<view class="text">点击更换头像</view>
		</view>
	</view>
</template>

<script>
import md5 from '@/hybrid/html/js/md5.js';
import { imgUrl, baseUrl } from '@/config.js';
import { apiPostInfoUpdate } from '@/api/me.js';
import { apiPostUpLoadCreate } from '@/api/upLoad.js';
export default {
	data() {
		return {
			info: { upload_avatar: { path_text: '' } },
			md5: '',
			nameMd5: '',
			size: '',
			file: {},
			name: '',
			type: ''
		};
	},
	props: {},
	mounted() {
		this.info = uni.getStorageSync('userinfo');
	},
	methods: {
		// 选择文件
		handleUpHeaderImg() {
			const that = this;
			uni.chooseImage({
				count: 1,
				success: function(chooseImageRes) {
					uni.showLoading({
						title: '上传头像中'
					});
					that.formetData(chooseImageRes)
						.then(data => {
							// 检测
							console.log('检测图片',data)
							that.fileUpLoadTest(data)
								.then(() => {
									// 上传
									console.log('开始上传')
									that.fileUpLoad()
										.then(() => {
											console.log('上传成功')
											// 设置获取头像
											that.getImg()
												.then(resImg => {
													// 设置绑定头像
													that.setImg(resImg.data);
												})
												.catch(() => {
													uni.hideLoading();
												});
										})
										.catch(() => {
											uni.hideLoading();
										});
								})
								.catch(data => {
									// 设置绑定头像
									that.setImg(data.data);
								});
						})
						.catch(title => {
							uni.hideLoading();
							uni.showToast({
								icon: 'none',
								title: title
							});
						});
				}
			});
		},
		// 绑定头像
		setImg(data) {
			uni.hideLoading();
			apiPostUpLoadCreate({ ppvod_image_id: data.shareid, type: 1 }).then(res => {
				this.editInfo({ avatar_upload_id: res.data.id });
			});
		},
		// 绑定用户
		editInfo(obj) {
			apiPostInfoUpdate(obj).then(res => {
				uni.showToast({
					title: '头像修改成功'
				});
			});
		},
		// 获取头像
		getImg() {
			const that = this;
			return new Promise(function(res, rej) {
				that.apiPpvod({
					status: 'chunksMerge',
					name: that.md5,
					uniqueFileName: that.md5,
					category: '默认',
					chunks: 1,
					md5: that.md5,
					ext: that.type
				}).then(infoData => {
					res(infoData);
				});
			});
		},
		// 上传
		fileUpLoad() {
			const that = this;
			return new Promise(function(res, rej) {
				let data = {
					userId: 'the_user',
					md5: that.md5,
					uniqueFileName: that.md5,
					name: that.name,
					type: 'image/' + that.type,
					size: that.size,
					chunk: 0
				};
				uni.uploadFile({
					url: imgUrl,
					files: [{ name: 'file', uri: that.file }],
					formData: data,
					success: function(r) {
						if (r.data == 'ok') {
							res();
						}
					}
				});
			});
		},
		// 检测
		fileUpLoadTest(data) {
			const that = this;
			return new Promise(function(res, rej) {
				let putData = {
					status: 'chunkCheck',
					name: that.md5,
					chunkIndex: 0,
					size: that.size
				};
				that.apiPpvod(data).then(data => {
					if (!data.data.ifExist) {
						that.apiPpvod(putData).then(testData => {
							res();
						});
						return;
					}
					rej(data);
				});
			});
		},

		// 处理数据
		formetData(chooseImageRes) {
			const that = this;
			return new Promise(function(res, rej) {
				let filePaths = chooseImageRes.tempFilePaths[0];
				that.size = chooseImageRes.tempFiles[0].size;
				console.log(chooseImageRes.tempFiles[0]);
				if (that.size > 1024 * 1024) {
					rej('头像大于1M');
				}
				// 文件md5
				let paths = filePaths.split('/');
				that.name = paths[paths.length - 1];
				that.file = filePaths;
				that.nameMd5 = md5(that.name);
				that.type = that.name.split('.')[that.name.split('.').length - 1];
				console.log('.bmp.jpg.png.jpeg'.indexOf(that.type))
				if ('.bmp.jpg.png.jpeg'.indexOf(that.type) < 0) {
					rej('图片格式不对');
					return 
				}
				that.info.upload_avatar = {};
				that.info.upload_avatar['path_text'] = filePaths;
				let datas = {
					status: 'md5Check',
					name: that.name,
					md5: '',
					uploadkey: 'the_user'
				};

				plus.io.getFileInfo({
					filePath: filePaths,
					digestAlgorithm: 'md5',
					success: function(data) {
						datas.md5 = that.md5 = data.digest.toLocaleLowerCase();
						res(datas);
					}
				});
			});
		},
		// 处理api
		apiPpvod(data) {
			return new Promise(function(res, rej) {
				uni.request({
					url: imgUrl,
					data: data,
					method: 'get',
					dataType: 'json',
					success: function(data) {
						res(data);
					},
					file: function(e) {
						rej(e);
					}
				});
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.handerimg {
	border-bottom: 1px solid #1c1b2b;
	margin-bottom: 40upx;
}
.imgs {
	background: #000;
	border-radius: 50%;
	width: 100upx;
	height: 100upx;
	overflow: hidden;
	display: flex;
	align-items: center;
	justify-content: center;
	margin: 40upx auto;
}

.box {
	.text {
		font-size: 12px;
		color: rgba(116, 115, 132, 1);
		margin-bottom: 80upx;
	}
}
.md5web {
	width: 100upx;
	height: 100upx;
	background: red;
}
</style>
